package org.word.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.thymeleaf.context.Context;
import org.thymeleaf.spring5.SpringTemplateEngine;
import org.word.service.WordService;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Map;

/**
 * Swagger 文档导出 Word 控制器
 *
 * @author XiuYin.Cui
 * @date 2018/1/11.
 */
@Api(tags = "Swagger 文档导出 Word 控制器")
@Controller
@RequestMapping(value = "/api/word/download")
public class WordController {
    /**
     * 默认Swagger JSON文件
     */
    @Value("${swagger.url}")
    private String swaggerUrl;
    /**
     * 默认文件名
     */
    private String filename = "Swagger Word API";

    @Autowired
    private WordService tableService;
    @Autowired
    private SpringTemplateEngine springTemplateEngine;

    /**
     * 通过 Swagger JSON URL 下载 doc 文档
     *
     * @param model
     * @param url      Swagger JSON资源地址
     * @param response
     */
    @ApiOperation(value = "通过 Swagger JSON URL 下载 doc 文档")
    @GetMapping(value = "/url")
    @ResponseStatus(value = HttpStatus.OK)
    public void downloadWordByUrl(Model model, @ApiParam(value = "Swagger Url：如：http://192.168.1.5:8080/swagger-ui.html", required = true) @RequestParam String url
          , @ApiParam(value = "Word文档名") @RequestParam(required = false) String name, HttpServletResponse response) {
        generateModelData(model, url.replace("swagger-ui.html","v2/api-docs"));
        writeContentToResponse(model, name, response);
    }

    /**
     * 将 swagger json文件转换成 word文档并下载
     *
     * @param model
     * @param jsonFile 需要转换成 word 文档的swagger json文件
     * @param response
     * @return
     */
    @ApiOperation(value = "通过 Swagger JSON 文件 下载 doc 文档")
    @PostMapping(value = "/file")
    @ResponseStatus(value = HttpStatus.OK)
    public void downloadWordByFile(Model model, @ApiParam(value = "Swagger JSON文件", required = true) @RequestPart("jsonFile") MultipartFile jsonFile
          , @ApiParam(value = "Word文档名") @RequestParam(required = false) String name, HttpServletResponse response) {
        generateModelData(model, jsonFile);
        writeContentToResponse(model, name, response);
    }

    /**
     * 将 swagger json字符串转换成 word文档并下载
     *
     * @param model
     * @param jsonStr  需要转换成 word 文档的swagger json字符串
     * @param response
     * @return
     */
    @ApiOperation(value = "通过 Swagger JSON 字符串 下载 doc 文档")
    @PostMapping(value = "/json")
    @ResponseStatus(value = HttpStatus.OK)
    public void downloadWordByJson(Model model, @ApiParam(value = "Swagger JSON字符串", required = true) @Valid @RequestBody String jsonStr
          , @ApiParam(value = "Word文档名") @RequestParam(required = false) String name, HttpServletResponse response) {
        generateModelDataOfJsonStr(model, jsonStr);
        writeContentToResponse(model, name, response);
    }

    /**
     * 封装视图数据
     *
     * @param model
     * @param url
     */
    private void generateModelData(Model model, String url) {
        url = StringUtils.defaultIfBlank(url, swaggerUrl);
        Map<String, Object> result = tableService.tableList(url);
        model.addAttribute("url", url);
        model.addAllAttributes(result);
    }

    /**
     * 为JSON转换Word封装视图数据
     *
     * @param model
     * @param jsonStr
     */
    private void generateModelDataOfJsonStr(Model model, String jsonStr) {
        Map<String, Object> result = tableService.tableListFromString(jsonStr);
        model.addAttribute("url", "http://");
        model.addAllAttributes(result);
    }

    /**
     * 为JSON文件转换word封装视图数据
     *
     * @param model
     * @param jsonFile
     */
    private void generateModelData(Model model, MultipartFile jsonFile) {
        Map<String, Object> result = tableService.tableList(jsonFile);
        model.addAttribute("url", "http://");
        model.addAllAttributes(result);
    }

    /**
     * 写入响应数据到Response
     *
     * @param model
     * @param name
     * @param response
     */
    private void writeContentToResponse(Model model, String name, HttpServletResponse response) {
        Context context = new Context();
        context.setVariables(model.asMap());
        String content = springTemplateEngine.process("word", context);
        response.setContentType("application/octet-stream;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        try (BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream())) {
            response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(StringUtils.defaultIfBlank(name, filename) + ".doc", "utf-8"));
            byte[] bytes = content.getBytes();
            bos.write(bytes, 0, bytes.length);
            bos.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
